package com.erik.lin.controller;

import com.erik.lin.orm.po.ApiPo;
import com.erik.lin.service.ApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Erik on 2017/4/9.
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private ApiService apiService;

    @RequestMapping(value = "/search/{id}")
    public @ResponseBody
    ApiPo findApiById(@PathVariable("id") String id) {
        return apiService.getApiById(id);
    }

    @RequestMapping(value = "/search")
    public @ResponseBody List<ApiPo> findApisByApiLabel(@RequestParam String apiLabel) {
        return apiService.getApisByApiLabel(apiLabel);
    }

    @RequestMapping(value =  "/save", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> save(@RequestBody ApiPo po) {
        Map rs = new HashMap<String, Object>();
        try {
            apiService.save(po);
            rs.put("success", true);
        }catch (Exception e) {
            rs.put("success", false);
            rs.put("msg", e.getMessage());
            e.printStackTrace();
        }finally {
            return rs;
        }
    }

    @RequestMapping(value =  "/update", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> update(@RequestBody ApiPo po) {
        Map rs = new HashMap<String, Object>();
        try {
            apiService.update(po);
            rs.put("success", true);
        }catch (Exception e) {
            rs.put("success", false);
            rs.put("msg", e.getMessage());
            e.printStackTrace();
        }finally {
            return rs;
        }
    }

    @RequestMapping(value =  "/deleteById/{id}", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> deleteById(@PathVariable("id") String id) {
        Map rs = new HashMap<String, Object>();
        try {
            apiService.deleteById(id);
            rs.put("success", true);
        }catch (Exception e) {
            rs.put("success", false);
            rs.put("msg", e.getMessage());
            e.printStackTrace();
        }finally {
            return rs;
        }
    }
}
